<template>
  <div class="review-applications">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1>审核申请</h1>
          <div class="user-info">
            <span>欢迎，{{ tutorName }}</span>
            <el-button link @click="logout">退出登录</el-button>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="250px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="dashboard">
              <el-icon><DataBoard /></el-icon>
              <span>仪表板</span>
            </el-menu-item>
            <el-menu-item index="review-applications">
              <el-icon><Document /></el-icon>
              <span>审核申请</span>
            </el-menu-item>
            <el-menu-item index="scoreboard">
              <el-icon><Trophy /></el-icon>
              <span>奖学金排名</span>
            </el-menu-item>
            <el-menu-item index="course-score-management">
              <el-icon><Edit /></el-icon>
              <span>成绩管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <div class="review-content">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>申请列表</span>
                  <div class="filters">
                    <el-input
                      v-model="searchKeyword"
                      placeholder="搜索学号或奖学金ID"
                      style="width: 200px; margin-right: 10px;"
                      @keyup.enter="handleSearch"
                    />
                    <el-button type="primary" @click="handleSearch" style="margin-right: 10px;">
                      搜索
                    </el-button>
                    <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleSearch">
                      <el-option label="全部" value="" />
                      <el-option label="待审核" value="pending" />
                      <el-option label="已通过" value="approved" />
                      <el-option label="已拒绝" value="rejected" />
                    </el-select>
                  </div>
                </div>
              </template>
              
              <el-table :data="applications" style="width: 100%" v-loading="loading">
                <el-table-column prop="studentName" label="学生姓名" width="120" />
                <el-table-column prop="studentId" label="学号" width="120" />
                <el-table-column prop="scholarshipName" label="奖学金名称" width="150" />
                <el-table-column prop="applyTime" label="申请时间" width="180" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button 
                      size="small" 
                      @click="viewDetails(scope.row)"
                    >
                      查看详情
                    </el-button>
                    <el-button 
                      v-if="scope.row.status === '申请中'"
                      size="small" 
                      type="success" 
                      @click="approveApplication(scope.row)"
                    >
                      通过
                    </el-button>
                    <el-button 
                      v-if="scope.row.status === '申请中'"
                      size="small" 
                      type="danger" 
                      @click="rejectApplication(scope.row)"
                    >
                      拒绝
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分页组件 -->
              <div style="margin-top: 20px; text-align: right;">
                <el-pagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="total"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-container>
    
    <!-- 申请详情对话框 -->
    <el-dialog 
      v-model="detailsVisible" 
      title="申请详情" 
      width="600px"
    >
      <div v-if="selectedApplication" class="application-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">{{ selectedApplication.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ selectedApplication.studentId }}</el-descriptions-item>
          <el-descriptions-item label="奖学金名称">{{ selectedApplication.scholarshipName }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ selectedApplication.applyTime }}</el-descriptions-item>
          <el-descriptions-item label="申请理由" :span="2">{{ selectedApplication.reason }}</el-descriptions-item>
          <el-descriptions-item label="联系方式" :span="2">{{ selectedApplication.contact }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataBoard, Document, Trophy, Edit } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const activeMenu = ref('review-applications')
const tutorName = ref(localStorage.getItem('name') || '导师')
const loading = ref(false)
const applications = ref([])
const statusFilter = ref('')
const detailsVisible = ref(false)
const selectedApplication = ref(null)

// 分页相关变量
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedStatus = ref('')
const searchKeyword = ref('')

const handleMenuSelect = (index) => {
  if (index === 'dashboard') {
    router.push('/professor/dashboard')
  } else if (index === 'scoreboard') {
    router.push('/professor/scoreboard')
  } else if (index === 'course-score-management') {
    router.push('/professor/course-score-management')
  } else if (index === 'review-applications') {
    router.push('/professor/review-applications')
  }
}

const logout = () => {
  localStorage.clear()
  router.push('/login')
}

const getStatusType = (status) => {
  switch (status) {
    case '申请中':
      return 'warning'
    case '已通过':
      return 'success'
    case '已拒绝':
      return 'danger'
    default:
      return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case '申请中':
      return '待审核'
    case '已通过':
      return '已通过'
    case '已拒绝':
      return '已拒绝'
    default:
      return '未知'
  }
}

const loadApplications = async () => {
  loading.value = true
  try {
    // 状态映射
    let statusParam = ''
    if (statusFilter.value === 'pending') {
      statusParam = '申请中'
    } else if (statusFilter.value === 'approved') {
      statusParam = '已通过'
    } else if (statusFilter.value === 'rejected') {
      statusParam = '已拒绝'
    }
    
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      status: statusParam,
      keyword: searchKeyword.value
    }
    
    const response = await axios.get('/scholarship-applications', { params })
    console.log('接口返回数据:', response.data)
    // 获取学生和奖学金信息
    const [studentsResponse, scholarshipsResponse] = await Promise.all([
      axios.get('/students'),
      axios.get('/scholarships')
    ])
    const students = studentsResponse.data
    const scholarships = scholarshipsResponse.data
    // 兼容数组或分页对象
    const list = Array.isArray(response.data) ? response.data : (response.data.content || [])
    applications.value = list.map(app => {
      const student = students.find(s => s.studentId === app.studentId)
      const scholarship = scholarships.find(s => s.scholarshipId === app.scholarshipId)
      return {
        ...app,
        studentName: student ? student.name : app.studentId,
        scholarshipName: scholarship ? scholarship.name : app.scholarshipId,
        applyTime: app.applyDate ? new Date(app.applyDate).toLocaleDateString('zh-CN') : ''
      }
    })
    total.value = list.length
  } catch (error) {
    console.error('加载申请数据失败:', error)
    ElMessage.error('加载申请数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索和筛选时重置到第一页
const handleSearch = () => {
  currentPage.value = 1
  loadApplications()
}

// 分页大小变化
const handleSizeChange = () => {
  currentPage.value = 1
  loadApplications()
}

// 当前页变化
const handleCurrentChange = () => {
  loadApplications()
}

const viewDetails = (application) => {
  selectedApplication.value = application
  detailsVisible.value = true
}

const approveApplication = async (application) => {
  try {
    await ElMessageBox.confirm('确定要通过这个申请吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.put(`/scholarship-applications/${application.applicationId}/approve`)
    console.log('审核通过响应:', response)
    ElMessage.success('申请已通过')
    loadApplications()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      let errorMessage = '审核失败'
      if (error.response && error.response.data) {
        errorMessage = error.response.data
      } else if (error.message) {
        errorMessage = error.message
      }
      ElMessage.error(errorMessage)
    }
  }
}

const rejectApplication = async (application) => {
  try {
    await ElMessageBox.confirm('确定要拒绝这个申请吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.put(`/scholarship-applications/${application.applicationId}/reject`)
    console.log('审核拒绝响应:', response)
    ElMessage.success('申请已拒绝')
    loadApplications()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      let errorMessage = '审核失败'
      if (error.response && error.response.data) {
        errorMessage = error.response.data
      } else if (error.message) {
        errorMessage = error.message
      }
      ElMessage.error(errorMessage)
    }
  }
}

onMounted(() => {
  loadApplications()
})
</script>

<style scoped>
.review-applications {
  height: 100vh;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.sidebar {
  background: #f5f7fa;
  border-right: 1px solid #e6e6e6;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
  background: #f0f2f5;
}

.review-content {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  display: flex;
  gap: 10px;
}

.application-details {
  padding: 20px 0;
}
</style> 